package com.snake.user.repository;

import com.snake.context.ComponentContext;
import com.snake.user.model.User;
import com.snake.user.sql.DBConnectionManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author xsyang
 * @Title:
 * @date 2021-03-0311:32
 */
public class UserRepositoryImpl implements UserRepository{

    private final DBConnectionManager dbConnectionManager;

    public UserRepositoryImpl() {
        this.dbConnectionManager = ComponentContext.getInstance().getComponent("bean/DBConnectionManager");
    }

    private Connection getConnection() {
        return dbConnectionManager.getConnection();
    }

    private static final String INSERT_USER_DML_SQL =
            "INSERT INTO users(username,password) VALUES (?,?)";


    @Override
    public int save(User user) {
        try (Connection conn = getConnection();
             PreparedStatement statement = conn.prepareStatement(INSERT_USER_DML_SQL)){
            statement.setString(1,user.getUsername());
            statement.setString(2,user.getPassword());
            return statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
